#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <string.h>
#include "ThreadPool.hpp"
#include "FileSystem.hpp"

// 函数：打印帮助信息
void print_help() {
    std::cout << "\n--- Simple File System Simulator ---\n";
    std::cout << "Available commands:\n";
    std::cout << "  login <user> <pass>    - Log in or register a new user.\n";
    std::cout << "  logout                   - Log out the current user.\n";
    std::cout << "  dir                      - List files in the current directory.\n";
    std::cout << "  create <file> <prot>     - Create a new file (prot: 1=r, 2=w, 3=rw).\n";
    std::cout << "  delete <file>            - Delete a file.\n";
    std::cout << "  open <file>              - Open a file.\n";
    std::cout << "  close <file>             - Close a file.\n";
    std::cout << "  read <file>              - Read content from a file.\n";
    std::cout << "  write <file> \"<content>\" - Write content to a file (content in quotes).\n";
    std::cout << "  help                     - Show this help message.\n";
    std::cout << "  exit                     - Exit the simulator.\n";
    std::cout << "------------------------------------\n";
}

int main(int argc, char **argv) {

    if(argc < 2) 
    {
        std::cout << "Usage: " << argv[0] << " 线程数\n";
        return -1;
    }
    // if(strncmp(argv[2],"-help",5) == 1){
    //     std::cout << "Usage: " << argv[0] << " 线程数\n";
    //     return 0;
    // }
    // 创建一个拥有4个工作线程的线程池
    int nr_thread = std::stoi(argv[1]);
    ThreadPool pool(nr_thread);
    // 获取文件系统的单例实例
    FileSystem& fs = FileSystem::instance();

    print_help();

    std::string line;
    while (true) {
        std::cout << "> ";
        if (!std::getline(std::cin, line)) {
            break; // 如果输入流结束（例如 Ctrl+D），则退出
        }

        std::stringstream ss(line);
        std::string command;
        ss >> command;

        if (command == "exit") {
            break;
        } else if (command == "help") {
            print_help();
        } else if (command == "login") {
            std::string user, pass;
            ss >> user >> pass;
            if (user.empty() || pass.empty()) {
                std::cout << "[ERROR] Usage: login <username> <password>\n";
                continue;
            }
            pool.enqueue([&fs, user, pass] { fs.login(user, pass); });
        } else if (command == "logout") {
            pool.enqueue([&fs] { fs.logout(); });
        } else if (command == "dir") {
            pool.enqueue([&fs] { fs.dir(); });
        } else if (command == "create") {
            std::string file;
            int prot;
            ss >> file >> prot;
            if (file.empty() || !(prot >= 1 && prot <= 3)) {
                std::cout << "[ERROR] Usage: create <filename> <protection_code (1-3)>\n";
                continue;
            }
            pool.enqueue([&fs, file, prot] { fs.create(file, prot); });
        } else if (command == "delete") {
            std::string file;
            ss >> file;
            if (file.empty()) {
                 std::cout << "[ERROR] Usage: delete <filename>\n";
                 continue;
            }
            pool.enqueue([&fs, file] { fs.del(file); });
        } else if (command == "open") {
            std::string file;
            ss >> file;
            if (file.empty()) {
                 std::cout << "[ERROR] Usage: open <filename>\n";
                 continue;
            }
            pool.enqueue([&fs, file] { fs.open(file); });
        } else if (command == "close") {
            std::string file;
            ss >> file;
            if (file.empty()) {
                 std::cout << "[ERROR] Usage: close <filename>\n";
                 continue;
            }
            pool.enqueue([&fs, file] { fs.close(file); });
        } else if (command == "read") {
            std::string file;
            ss >> file;
            if (file.empty()) {
                 std::cout << "[ERROR] Usage: read <filename>\n";
                 continue;
            }
            pool.enqueue([&fs, file] { fs.read(file); });
        } else if (command == "write") {
             std::string file;
             std::string content;
             ss >> file;
             // 读取带引号的内容
             if (ss.peek() == ' ') ss.ignore();
             if (ss.peek() == '"') {
                 ss.ignore(); // 跳过第一个引号
                 std::getline(ss, content, '"');
             } else {
                 std::getline(ss, content);
             }
             
             if (file.empty()) {
                 std::cout << "[ERROR] Usage: write <filename> \"<content>\"\n";
                 continue;
             }
             pool.enqueue([&fs, file, content] { fs.write(file, content); });
        }
        else {
            if(!command.empty()) {
               std::cout << "[ERROR] Unknown command: '" << command << "'. Type 'help' for a list of commands.\n";
            }
        }
        
        // 短暂休眠以确保任务输出有机会显示
        // 这是一个简单的同步方法，更复杂的方法可以使用 future/promise
        usleep(10000); 
    }

    std::cout << "Shutting down the file system...\n";
    return 0;
}
